package com.mmy.fta.cargo.web.rest;

import com.mmy.fta.cargo.server.dto.ShipperCargoDTO;
import com.mmy.fta.cargo.server.dto.CargoBlackboardPageDTO;
import com.mmy.fta.cargo.server.dto.CargoBlackboardPageRequestDTO;
import com.mmy.fta.cargo.server.entity.CargoInfoEntity;
import com.mmy.fta.cargo.server.mapper.CargoInfoEntityMapper;
import com.mmy.fta.cargo.server.service.CargoBlackboardPageService;
import com.mmy.fta.cargo.server.service.ComputeDistanceMeter;
import com.mmy.fta.cargo.server.service.PublishCargoInfoService;
import com.mmy.fta.cargo.web.enums.DefaultResponseCode;
import com.mmy.fta.cargo.web.request.CargoBlackboardPageRequest;
import com.mmy.fta.cargo.web.request.DeleteCargoRequest;
import com.mmy.fta.cargo.web.request.EditCargoRequest;
import com.mmy.fta.cargo.web.response.CargoBlackboardPageResponse;
import com.mmy.fta.cargo.web.response.EditCargoResponse;
import com.mmy.fta.cargo.web.response.PublishCargoResponse;
import com.mmy.fta.usercenter.api.UserService;
import com.ymm.common.rpc.YmmResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author guohao.xie
 * @apiNote
 * @exportable
 * @since 2021/10/22
 */
@RestController
@RequestMapping(value = "/blackboard")
@Slf4j
public class CargoBlackboardController {
    @Reference
    UserService userService;

    @Autowired
    CargoBlackboardPageService cargoBlackboardPageService;

    @Autowired
    PublishCargoInfoService publishCargoInfoService;

    @Autowired
    CargoInfoEntityMapper cargoInfoEntityMapper;

    @Autowired
    ComputeDistanceMeter computeDistanceMeter;

    /**
     * 货主发货首页小黑板
     */
    @PostMapping(value = "cargoBlackboard")
    public YmmResult<CargoBlackboardPageResponse> getPulishCargo(@RequestBody CargoBlackboardPageRequest cargoBlackboardPageRequest) {
        try {
            if (null == cargoBlackboardPageRequest) {
                return YmmResult.failResult(0, "请求参数为空");
            }
            //查询剩余发货次数和货主id
            ShipperCargoDTO shipperCargoDTO = publishCargoInfoService.sendCargoMsg(cargoBlackboardPageRequest.getOpenId());

            CargoBlackboardPageRequestDTO cargoBlackboardPageRequestDTO = new CargoBlackboardPageRequestDTO();
            BeanUtils.copyProperties(cargoBlackboardPageRequest, cargoBlackboardPageRequestDTO);
            cargoBlackboardPageRequestDTO.setShipperIdNo(shipperCargoDTO.getIdentityNo());

            CargoBlackboardPageDTO cargoBlackboardPageDTO = cargoBlackboardPageService.getCargoPageInfo(cargoBlackboardPageRequestDTO);

            CargoBlackboardPageResponse cargoBlackboardPageResponse = new CargoBlackboardPageResponse();

            //数据总条数
            int totalSize = cargoBlackboardPageService.getCargoPageTotalSize(cargoBlackboardPageRequest.getOpenId());
            cargoBlackboardPageDTO.setTotalSize(totalSize);
            BeanUtils.copyProperties(cargoBlackboardPageDTO, cargoBlackboardPageResponse);

            return YmmResult.succResult(cargoBlackboardPageResponse);

        } catch (Exception e) {
            log.info(e.toString());
            return YmmResult.failResult(0, "调用失败");
        }

    }


    /**
     * 货主发货历史
     */
    @PostMapping(value = "cargoBlackboardHistory")
    public YmmResult<CargoBlackboardPageResponse> getHistoryPulish(@RequestBody CargoBlackboardPageRequest cargoBlackboardPageRequest) {
        try {
            if (null == cargoBlackboardPageRequest) {
                return YmmResult.failResult(0, "请求参数为空");
            }
            //查询剩余发货次数和货主id
            ShipperCargoDTO shipperCargoDTO = publishCargoInfoService.sendCargoMsg(cargoBlackboardPageRequest.getOpenId());
            CargoBlackboardPageRequestDTO cargoBlackboardPageRequestDTO = new CargoBlackboardPageRequestDTO();
            BeanUtils.copyProperties(cargoBlackboardPageRequest, cargoBlackboardPageRequestDTO);
            cargoBlackboardPageRequestDTO.setShipperIdNo(shipperCargoDTO.getIdentityNo());

            CargoBlackboardPageDTO cargoBlackboardPageDTO = cargoBlackboardPageService.getHistoryCargoPageInfo(cargoBlackboardPageRequestDTO);
            CargoBlackboardPageResponse cargoBlackboardPageResponse = new CargoBlackboardPageResponse();
            //数据总条数
            int totalSize = cargoBlackboardPageService.getHistoryCargoPageTotalSize(shipperCargoDTO.getIdentityNo());
            cargoBlackboardPageDTO.setTotalSize(totalSize);
            BeanUtils.copyProperties(cargoBlackboardPageDTO, cargoBlackboardPageResponse);
            return YmmResult.succResult(cargoBlackboardPageResponse);

        } catch (Exception e) {
            return YmmResult.failResult(0, "调用失败");
        }
    }

    /**
     * 货主编辑和重新上架货源信息
     */
    @PostMapping(value = "editCargo")
    public YmmResult<EditCargoResponse> editCargo(@RequestBody EditCargoRequest editCargoRequest) {
        EditCargoResponse response = new EditCargoResponse();
        try {
            if (null == editCargoRequest || Objects.isNull(editCargoRequest.getCargoId())) {
                response.setErrorMsg("请求参数不全");
                response.respond(DefaultResponseCode.PARAMS_ERROR);
                response.setResult(0);
                return YmmResult.succResult(response);
            }
            CargoInfoEntity cargoInfoEntity = new CargoInfoEntity();
            BeanUtils.copyProperties(editCargoRequest, cargoInfoEntity);

            CargoInfoEntity cargoInfoEntity1 = cargoInfoEntityMapper.selectCargoInfobyCargoId(editCargoRequest.getCargoId());

            cargoInfoEntity.setEstimateDistance(cargoInfoEntity1.getEstimateDistance());
            cargoInfoEntity.setStandardCargo(cargoInfoEntity1.getStandardCargo());

            //计算公里数
            double meter1 = computeDistanceMeter.getDistanceMeter(
                    new GlobalCoordinates(Double.parseDouble(editCargoRequest.getLoadLatitude()), Double.parseDouble(editCargoRequest.getLoadLongitude())),
                    new GlobalCoordinates(Double.parseDouble(editCargoRequest.getUnloadLatitude()), Double.parseDouble(editCargoRequest.getUnloadLongitude())),
                    Ellipsoid.Sphere);
            cargoInfoEntity.setMileage(meter1);
            int result;

            if(Objects.isNull(cargoInfoEntity.getEstimateDistance())){
                cargoInfoEntity.setEstimateDistance(0);
            }


            if(Objects.equals(editCargoRequest.getOrderNumber(),"0")){
                //编辑货源
                if(Objects.equals(cargoInfoEntity.getTruckType(),"冷藏车")){
                    // 冷链货主 发冷链
                    if(userService.queryShipperIsColdMember(editCargoRequest.getOpenId())){
                        cargoInfoEntity.setStandardCargo(true);
                    }else {
                        cargoInfoEntity.setStandardCargo(false);
                    }
                    cargoInfoEntity.setBuyoutPrice(true);
                }else{
                    cargoInfoEntity.setBuyoutPrice(false);
                }
                result = cargoBlackboardPageService.editCargo(cargoInfoEntity);
            }else{
                //重新上架货源
                if(Objects.equals(cargoInfoEntity.getTruckType(),"冷藏车")){
                    // 冷链货主 发冷链
                    if(userService.queryShipperIsColdMember(editCargoRequest.getOpenId())){
                        cargoInfoEntity.setStandardCargo(true);
                    }else {
                        cargoInfoEntity.setStandardCargo(false);
                    }
                    cargoInfoEntity.setBuyoutPrice(true);
                }else{
                    cargoInfoEntity.setBuyoutPrice(false);
                }
                result = cargoBlackboardPageService.upCargo(cargoInfoEntity);
            }
            if (Objects.equals(result, 0)) {
                response.setResult(0);
                response.setErrorMsg("更新失败");
                return YmmResult.succResult(response);
            }


            response.setResult(1);
            response.setErrorMsg("更新成功");
            return YmmResult.succResult(response);

        } catch (Exception e) {
            return YmmResult.failResult(0, "调用失败");
        }
    }

    /**
     * 货主删除货源
     */
    @PostMapping(value = "deleteCargo")
    public YmmResult<EditCargoResponse> deleteCargo(@RequestBody DeleteCargoRequest deleteCargoRequest) {
        EditCargoResponse response = new EditCargoResponse();
        try {
            if (Objects.isNull(deleteCargoRequest)) {
                return YmmResult.failResult(0, "请求参数为空");
            }
            int result = cargoBlackboardPageService.deleteCargo(deleteCargoRequest.getCargoId());
            if (Objects.equals(result, 0)) {
                response.setResult(0);
                return YmmResult.succResult(response);
            }
            response.setResult(1);
            return YmmResult.succResult(response);

        } catch (Exception e) {
            return YmmResult.failResult(0, "调用失败");
        }
    }

    /**
     * 货主重新上架货源信息
     */
    @PostMapping(value = "upCargo")
    public YmmResult<EditCargoResponse> upCargo(@RequestBody EditCargoRequest editCargoRequest) {
        EditCargoResponse response = new EditCargoResponse();
        try {
            if (null == editCargoRequest || Objects.isNull(editCargoRequest.getCargoId())) {
                response.setErrorMsg("请求参数不全");
                response.respond(DefaultResponseCode.PARAMS_ERROR);
                response.setResult(0);
                return YmmResult.succResult(response);
            }
            CargoInfoEntity cargoInfoEntity = new CargoInfoEntity();
            BeanUtils.copyProperties(editCargoRequest, cargoInfoEntity);

            if(Objects.equals(cargoInfoEntity.getTruckType(),"冷藏车")){
                cargoInfoEntity.setBuyoutPrice(true);
            }else{
                cargoInfoEntity.setBuyoutPrice(false);
            }

            //计算公里数
            double meter1 = computeDistanceMeter.getDistanceMeter(
                    new GlobalCoordinates(Double.parseDouble(editCargoRequest.getLoadLatitude()), Double.parseDouble(editCargoRequest.getLoadLongitude())),
                    new GlobalCoordinates(Double.parseDouble(editCargoRequest.getUnloadLatitude()), Double.parseDouble(editCargoRequest.getUnloadLongitude())),
                    Ellipsoid.Sphere);
            cargoInfoEntity.setMileage(meter1);
            int result = cargoBlackboardPageService.editCargo(cargoInfoEntity);
            if (Objects.equals(result, 0)) {
                response.setResult(0);
                response.setErrorMsg("更新失败");
                return YmmResult.succResult(response);
            }
            response.setResult(1);
            response.setErrorMsg("更新成功");
            return YmmResult.succResult(response);

        } catch (Exception e) {
            return YmmResult.failResult(0, "调用失败");
        }
    }


    //获取两点之间距离
    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }

}
